<template>
  <div>

    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>学生图书管理</el-breadcrumb-item>
      <el-breadcrumb-item>借阅记录</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入图书名称"
                    clearable
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="openEnter">新建还书</el-button>
        </el-col>
      </el-row>
      <el-table
          :data="bookInfos.filter(data => !search || data.bookName.toLowerCase().includes(search.toLowerCase()))"
          stripe
          style="width: 100%"
      >
        <template slot="empty" v-if="bookInfos.length===0">
          <i class="el-icon-loading"></i>
          <span style="color:lightgreen">还没有图书借阅信息，快去借书吧...</span>
        </template>
        <el-table-column prop="isbn" label="图书ISBN" width="190" align="center"></el-table-column>
        <el-table-column prop="bookName" label="图书名称" width="150" align="center"></el-table-column>
        <el-table-column prop="bookAuthor" label="图书作者" width="150" align="center"></el-table-column>
        <el-table-column prop="borrow_date" label="图书借书时间" width="190" align="center"></el-table-column>
        <el-table-column prop="return_date" label="图书归还时间" width="190" align="center"></el-table-column>
        <el-table-column label="距离还书还剩几天" width="190" align="center">
          <template slot-scope="scope">
          <span
              :class="!!(parseInt((new Date(scope.row.return_date) - (new Date().getTime()))/(24*3600*1000))<0)?'returnDay-info':'remainDay-info'"
          >{{
              !!(parseInt((new Date(scope.row.return_date) - (new Date().getTime())) / (24 * 3600 * 1000)) > 0) ? `距离还书还有${parseInt((new Date(scope.row.return_date) - (new Date().getTime())) / (24 * 3600 * 1000))}天` : `距离还书日期已经过去了${-parseInt((new Date(scope.row.return_date) - (new Date().getTime())) / (24 * 3600 * 1000))}天，请尽快还书!`
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template slot="header" slot-scope="scope">
            <el-input v-model="search" size="small" placeholder="根据图书名称进行搜索..."/>
          </template>
<!--          <template slot-scope="scope">-->
<!--            <el-button type="success" size="small" round @click="returnBook(scope.row)">归还图书</el-button>-->
<!--          </template>-->
        </el-table-column>
      </el-table>
    </el-card>
    <!--        出库登记-->
    <el-dialog
        title="借书登记"
        :visible.sync="enterDialog"
        width="45%"
        @close="enterClose">
      <el-form
          :model="student"
          ref="enterRef"
          :rules="enterRules"
          label-width="90px"
          :inline="true">
        <p style="color: red">*请先放置学生卡</p>
        <el-form-item label="学生卡编号">
          <el-autocomplete
              v-model="student.email"
              :fetch-suggestions="querySearchAsync"
              placeholder="请先防置学生卡"
              @select="handleSelect">
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="student.username" :disabled="true" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="student.name" :disabled="true" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="student.roleName" :disabled="true" style="width: 220px"></el-input>
        </el-form-item>
        <el-divider></el-divider>
      </el-form>
      <el-form
          :model="returnbook"
          ref="shipRef"
          label-width="90px"
          :inline="true"
          v-if="student.username!=''"
      >
        <p style="color: red">*请先选择学生卡后，放置图书</p>

        <el-form-item label="图书编号">
          <el-autocomplete
              v-model="returnbook.rfid"
              :fetch-suggestions="querySearchAsync1"
              placeholder="请扫描图书标签"
              @select="handleSelect1">
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="isbn">
          <el-input v-model="returnbook.isbn" :disabled="true" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="书名">
          <el-input v-model="returnbook.title" :disabled="true" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="returnbook.author" :disabled="true" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="returnbook.press" :disabled="true" style="width: 220px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="enterDialog = false ,shipDialog = false">取 消</el-button>
                <el-button type="primary" @click="shipYes1">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
import dateUtils from "../../util/dateUtlis";
import {Message} from "element-ui";

export default {
  data() {
    return {
      //借阅的图书信息
      bookInfos: [],
      search: "",
      enterDialog: false,
      student: {
        email: '',
        name: '',
        username: '',
        roleName: ''
      },
      enterRules: {
        universal: [{required: true, message: '必填项', trigger: 'blur'}],
      },
      queryInfo1: {
        name: '',
        state: 2,
        isread: 1
      },
      studentquery: {
        name: '',
        state: 1,
        isread: 1
      },
      returnbook: {
        rfid: '',
        title: '',
        author: '',
        press: '',
        isbn: ''
      },
    };
  },
  computed: {
    // remainDay() {
    //   return;
    // }
  },
  methods: {
    async getAllBookBorrowInfos() {
      let _this = this,
          curr_user = this.$store.state.user.name;

      let rolename = this.$store.state.user.roleName;
      console.log(rolename);
      if (rolename == '系统管理员' || rolename == '超级管理员') {
        console.log("管理员专属通道")
        const res = await this.$http.post('/api/getAllBookBorrow').then(res => {
          console.log(res)
          if (res && res.status === 200) {
            _this.bookInfos = res.obj;
            //转换为时间戳进行排序
            for (var i = 0; i < _this.bookInfos.length; i++) {
              _this.bookInfos[i].borrow_date = _this.dateToTime(
                  _this.bookInfos[i].borrow_date
              );
            }
            _this.bookInfos.sort(function (a, b) {
              return b.borrow_date > a.borrow_date ? -1 : 1;
            });
          }
          //再将时间戳变换为标准时间
          _this.bookInfos.forEach(item => {
            item.borrow_date = dateUtils.formatStandard(item.borrow_date);
          });
        })
            .catch(error => {
              console.log(error);
            });
      } else {
        const res = await this.$http.post('/api/getAllBookBorrowInfos', {
          username: curr_user
        }).then(res => {
          console.log(res)
          if (res && res.status === 200) {
            _this.bookInfos = res.obj;
            //转换为时间戳进行排序
            for (var i = 0; i < _this.bookInfos.length; i++) {
              _this.bookInfos[i].borrow_date = _this.dateToTime(
                  _this.bookInfos[i].borrow_date
              );
            }
            _this.bookInfos.sort(function (a, b) {
              return b.borrow_date > a.borrow_date ? -1 : 1;
            });
          }
          //再将时间戳变换为标准时间
          _this.bookInfos.forEach(item => {
            item.borrow_date = dateUtils.formatStandard(item.borrow_date);
          });
        })
            .catch(error => {
              console.log(error);
            });
      }
    },
    openEnter() {
      this.enterDialog = true;
      // this.shipDialog = true;
    },
    //远程查询学生卡
    async querySearchAsync(queryString, cb) {
      this.studentquery.name = queryString;
      console.log('查询学生信息');
      console.log(this.studentquery)
      const res = await this.$http.get('/employee/RFIDUser/', {params: this.studentquery});
      console.log(res);
      for (let i of res.obj) {
        i.value = i.username + ':' + i.name;
        // i.value = i.data;
      }
      cb(res.obj);
    },
    handleSelect(item) {
      this.student.email = item.email;
      this.student.roleName = item.roleName;
      this.student.name = item.name;
      this.student.username = item.username;
    },

    //远程查询Book
    async querySearchAsync1(queryString, cb) {
      this.queryInfo1.name = queryString;
      const res = await this.$http.get('/RFIDBook/', {params: this.queryInfo1});
      console.log(res);
      for (let i of res.obj) {
        i.value = i.title + ':' + i.author + i.press;
        // i.value = i.data;
      }
      cb(res.obj);
    },
    handleSelect1(item) {
      this.returnbook.rfid = item.rfid;
      this.returnbook.isbn = item.isbn;
      this.returnbook.title = item.title;
      this.returnbook.author = item.author;
      this.returnbook.press = item.press;
    },

    async shipYes1() {
      if (this.returnbook.rfid == '' || this.student.email == '') {
        Message.error("请查看是否确认学生卡或图书卡");
        return;
      }
      /*for (let book of this.books) {
        if (book.isbn == this.returnbook.isbn && book.num == 0) {
          Message.error("该图书太火爆，被借完了！");
          return;
        }
      }*/
      const res = await this.$http.post('/api/updateBkBrwRecord', {
        username: this.student.username,
        isbn: this.returnbook.isbn,
        rfid: this.returnbook.rfid,
        borrowdate: 0,
        returndate: 0,
        isreturn: 0
      });
      if (res && res.status === 200) {
        console.log('更新图书状态!')
        const res1 = await this.$http.post('/api/updateIsBrw', {
          isbn: this.returnbook.isbn,
          rfid: this.returnbook.rfid,
          isborrow:0
        })
        this.getAllBookBorrowInfos();
        this.enterClose();
        if (res1 && res1.status === 200) {
          //借阅成功，重新加载所有图书信息
          this.reloadTg = true;
          this.$message({
            type: "success",
            message: "还书成功！"
          });
          this.getAllBookBorrowInfos();
        } else {
          this.$message({
            type: "error",
            message: "还书失败！"
          });
        }
      }

      this.enterClose();
    },
    enterClose() {
      this.enterDialog = false;
      this.student = {
        email: '',
        name: '',
        username: '',
        roleName: '',
      };
      this.returnbook = {
        rfid: '',
        title: '',
        author: '',
        press: '',
        isbn: ''
      };
      //  this.query.id = '';
      this.warehouseId = '';
    },
    dateToTime(str) {
      return new Date(str.replace(/-/g, "/")).getTime(); //用/替换日期中的-是为了解决Safari的兼容
    },
    //归还图书
    async returnBook() {
      if (this.returnbook.rfid == '' || this.student.email == '') {
        Message.error("请查看是否确认学生卡或图书卡");
        return;
      }
      let _this = this;
      const res = await this.$http.post('/api/returnBook', {
        isbn: this.returnbook.isbn,
        rfid: this.returnbook.rfid
      }).then(res => {
        console.log(res.status);
        if (res && res.status === 200) {
          const res1 = this.$http.post('/api/updateIsReturn', {
            isbn: row.isbn
          }).then(res1 => {
            if (res1 && res1.status === 200) {
              _this.$message({
                type: "success",
                message: "图书归还成功!"
              });
              _this.getAllBookBorrowInfos();
            }
          })
              .catch(error => {
                console.log(error);
              });
        }
      })
          .catch(error => {
            console.log(error);
          });
    },
    remainDay(row) {
      let a = new Date(row.return_date) - new Date(row.borrow_date);
      console.log(parseInt(a / (24 * 60 * 60 * 1000)));
    }
  },
  mounted() {
    //组件加载时获取图书的信息
    this.getAllBookBorrowInfos();
  }
};
</script>

<style scoped>
.remainDay-info {
  color: green;
}

.returnDay-info {
  color: red;
}
</style>